package com.jingdianjichi.club.getway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关全局拦截器
 * @author 86156
 * @version 1.0
 * @date 2024-11-10 13:12
 */
@Component
public class LoginFilter implements GlobalFilter {

    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String path = request.getURI().getPath();
        // 如果是登录的话直接放行 - 白名单
        if(path.equals("/auth/user/doLogin")){
            chain.filter(exchange);
        }

        // 往请求头中添加loginId - 即微信登录的唯一标识 openId
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String loginId = (String)tokenInfo.getLoginId();
        if(StringUtils.isBlank(loginId)){
            throw new Exception("未获取到用户信息!");
        }
        mutate.header("loginId",loginId);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
